package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"
)

func main() {
	// go st()
	checkAndCreateFile()
	s_root_dir := "./html"
	initdb()
	go flow_control()

	// 使用 http.FileServer 来处理静态文件的请求
	fs := http.FileServer(http.Dir(s_root_dir))

	// 将所有请求的路径都指向 s_root_dir 目录
	http.Handle("/", fs)
	// 处理 /api/get/sn 路径的请求
	http.HandleFunc("/api/get/sn", func(w http.ResponseWriter, r *http.Request) {
		// 设置 CORS 响应头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		// 设置响应内容类型为 JSON
		w.Header().Set("Content-Type", "application/json")

		// 返回一些示例数据（假设返回一个 JSON 响应）
		w.Write([]byte(getMD5Hash()))
	})
	// 处理 /api/get/sn 路径的请求
	http.HandleFunc("/api/claen/cron", func(w http.ResponseWriter, r *http.Request) {
		// 设置 CORS 响应头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		// 设置响应内容类型为 JSON
		w.Header().Set("Content-Type", "application/json")
		exec.Command("sh", "-c", "sed -i '/reboot/d' "+cronFilePath).Start()

		// 返回一些示例数据（假设返回一个 JSON 响应）
		w.Write([]byte(`{"success": true, "msg": "Clean Reboot"}`))
	})

	http.HandleFunc("/api/get/Total", func(w http.ResponseWriter, r *http.Request) {
		// 设置 CORS 响应头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		result, err := runVnstatCommand()
		if err != nil {
			result = ""
		}
		jsonData := []byte(result)
		rx, tx := GetTotalTraffic(jsonData, "sipa_eth0")
		rxValue := int64(rx)
		txValue := int64(tx)

		jsonStr := GenerateTrafficJSON(rxValue, txValue)

		// 返回一些示例数据（假设返回一个 JSON 响应）
		w.Write([]byte(jsonStr))
	})
	http.HandleFunc("/api/get/set", func(w http.ResponseWriter, r *http.Request) {
		// 设置 CORS 响应头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		filePath := "/home/root/6789/6789.json"
		_, err := os.Stat(filePath)
		if os.IsNotExist(err) {
			// 文件不存在，直接返回预设的 JSON 数据
			result := struct {
				Much   int64 `json:"much"`
				Switch int64 `json:"switch"`
			}{
				Much:   0,
				Switch: 0,
			}
			jsonData, marshalErr := json.Marshal(result)
			if marshalErr != nil {
				http.Error(w, "Failed to marshal default data", http.StatusInternalServerError)
				return
			}
			w.Write(jsonData)
			return
		}

		// 文件存在，尝试读取文件
		data, err := ioutil.ReadFile(filePath)
		if err != nil {
			// 读取错误，返回预设的 JSON 数据
			result := struct {
				Much   int `json:"much"`
				Switch int `json:"switch"`
			}{
				Much:   0,
				Switch: 0,
			}
			jsonData, marshalErr := json.Marshal(result)
			if marshalErr != nil {
				http.Error(w, "Failed to marshal default data", http.StatusInternalServerError)
				return
			}
			w.Write(jsonData)
			return
		}

		// 成功读取文件，返回文件内容
		w.Write(data)
	})

	http.HandleFunc("/api/get/first-reboot", handleGetFirstRebootJob)
	http.HandleFunc("/api/set/total", handleSetluliang)

	http.HandleFunc("/api/set/reboot", handleSetReboot)
	http.HandleFunc("/api/upload", handleFileUpload) // 处理文件上传请求

	// 启动 HTTP 服务器
	port := ":6789"
	// fmt.Println("Starting server on", port)
	if err := http.ListenAndServe(port, nil); err != nil {
		// fmt.Println("Error starting server:", err)
	}

}

